/*
 * preQrcode 
 * 
 * generate qrcode after image process finished
 * 
 */

var winston = require("winston");
var gm = require("gm");
var path = require("path");
var mysql = require("mysql");
var Promise = require("bluebird");
var request = require("request");
var exec = require('child_process').exec;

var preQrcode = function(){
	if(!(this instanceof preQrcode))
		return new preQrcode();
};
module.exports = preQrcode;



preQrcode.prototype.process = function(config, fileName, dbConfig, extNameRE){
	this.config = config;
	this.dbConfig = dbConfig;
	this.fileName = fileName.replace(extNameRE, "_c$1");
	this.newFileName = fileName.replace(extNameRE, "_qr$1");
	this.query(path.basename(fileName));
}

preQrcode.prototype.genQrcode = function(){
	var self = this;
	var config = self.config;
	var fileName = self.fileName;
	var newFileName = self.newFileName;
	var style = self.style;
	var photoId = self.photoId;
	var eventId = self.eventId;
	var shareContent = '^(' + photoId + ')$';
	var qrconfig = config.genQrcode;
	request.post(qrconfig.host + "/share/" + eventId,
		 {form: {shareContent: shareContent}},
		 function(err, response, body){
		 	if(err){
		 		winston.error(err);
		 	}else{
			 	if (response.statusCode == 200) {
			 		if(typeof body === 'string'){
			 			body = JSON.parse(body);
			 		}
			    var qrcontent = qrconfig.host + "/share/" + body.uri_map;
			    qrcontent = encodeURIComponent(qrcontent);
			    var queryString = [];
			    if(qrconfig.width){
			    	queryString.push('width=' + qrconfig.width);
			    }
			    if(qrconfig.borderWidth){
			    	queryString.push('borderWidth=' + qrconfig.borderWidth);
			    }
			    if(qrconfig.borderColor){
			    	queryString.push('borderColor=' + encodeURIComponent(qrconfig.borderColor));
			    }
			    if(qrconfig.darkColor){
			    	queryString.push('darkColor=' + encodeURIComponent(qrconfig.darkColor));
			    }
			    if(qrconfig.lightColor){
			    	queryString.push('lightColor=' + encodeURIComponent(qrconfig.lightColor));
			    }
			    var qrcode = qrconfig.host + "/bqr/" + qrcontent + "?" + queryString.join("&");
			    var cmd = 'gm composite -geometry ' + qrconfig.position[style] + ' "' + qrcode + '" ' + fileName + ' ' + newFileName;
			    exec(cmd, function(err, stdout, stderr){
	            if(err){
	                winston.error( err);
	            }
	            if(stderr){
	                winston.error(stderr);  
	            }else{
	                winston.info("preQrgen completed.");
	            }
	        });
			    /**
			     * has error when using gm 
			     *
			     *
			    gm(fileName)
			    	.command('composite')
			    	.in('geometry', qrconfig.position[style])
			    	.in(qrcode)
			    	.write(newFileName, function(err){
			    		if(err){
			    			winston.error(err);
			    		}else{
			    			winston.info('preQrgen finished.');
			    		}
			    	});
			    */
			  }	
		 	}
			
	});

}

preQrcode.prototype.query = function(name){
	var self = this;
	var dbConfig = self.dbConfig;
	var connection = mysql.createConnection(dbConfig);
	var sql = 'select photo_id, event_id, is_portrait from photo_list where filename="' + name +'"';
	connection.query(sql, function(err, rows){
		if(err){
			winston.error( err );
		}else{
			self.style = rows[0].is_portrait == 1 ? "p" : "l";
			self.photoId = rows[0].photo_id;
			self.eventId = rows[0].event_id;
			self.genQrcode();
			connection.destroy();
		}
	});
}

